import {defineQuery, useQuery} from "@pinia/colada";
import {downloadFile} from "../api/file.ts";
import {ref} from "vue";
import {saveAs} from "file-saver"

export const useDownloadFile = defineQuery(() => {
    const downloadPath = ref<string>("")
    let fileName = '';

    let {isLoading, refetch} = useQuery({
        key: () => ['file', downloadPath.value],
        query: () => downloadFile(downloadPath.value).then(res => {
            saveAs(res.data, fileName + "." + downloadPath.value.split('.').at(-1))
        }),
        enabled: false,
        refetchOnWindowFocus: false,
        refetchOnMount: false,
        refetchOnReconnect: false
    });

    function setFileName(val: string) {
        fileName = val
    }


    return {
        downloadPath,
        isLoading,
        setFileName,
        refetch
    }
})